[BE101] 初探 PHP


Posted by yymarlerr on 2021-06-10

初探 PHP

從前端傳資料給後端

  • request 裡面會帶有 URL,可在 URL 後面接 query string 參數,像是 ?a=1,而這個參數會被自動存到 PHP的 $_GET 這個變數裡面
  • Server 看到此 URL 會去找對應的檔案

範例,URL: http://localhost:8080/Yide/index.php?a=3

<?php
    $a = 2;
  echo $a . "<br>";
  print_r($_GET);
?>

會得到:
2
Array ( [a] => 3 )

<?php
    $a = 2;
    echo $a . "<br>";
    print_r($_GET['a']);
?>

會得到:
2
3

  • 也可以用 issset() 這個函式來判斷是否有此參數,如果有傳 key 但是沒有 value,isset 的結果還是會是 true
<?php
    if (isset($_GET['a'])) {
    print_r($_GET['a']);
  }
?>

用表單來傳送資料

範例ㄧ

index.php 內容

<form method="GET" action="data.php">
  name: <input name="name" />
  age: <input name="age" />
  <input type="submit">
</form>

data.php 內容

<?php
    if (empty($_GET["name"]) || empty($_GET["age"]) {
    echo "資料有缺,請再次填寫";
  }

  echo "Hello" . $_GET(["name"]) . "<br>";
  echo "Your age is" . $_GET(["age"]) . "<br>";

?>

會得到:資料有缺,請再次填寫
Fatal error: Uncaught Error: Array callback has to contain indices 0 and 1 in /opt/lampp/htdocs/Yide/data.php:6 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/Yide/data.php on line 6
網址(可以看到後面有自動帶參數):http://localhost:8080/Yide/data.php?name=&age=

因為程式碼會繼續往下跑,所以會跳出其他錯誤訊息,可以用 exit() 這個函式或 else,跳出來。

<?php
    if (empty($_GET["name"]) || empty($_GET["age"])) {
    echo "資料有缺,請再次填寫";
    exit()
  }

  echo "Hello" . $_GET(["name"]) . "<br>";
  echo "Your age is" . $_GET(["age"]) . "<br>";

?>

範例二

  • 用 post
    index.php 內容
<form method="POST" action="data.php">
  name: <input name="name" />
  age: <input name="age" />
  <input type="submit">
</form>

data.php 內容

<?php
    if (empty($_POST["name"]) || empty($_POST["age"])) {
    echo "資料有缺,請再次填寫<br>";
    exit();
  }

  echo "Hello" . $_POST["name"] . "<br>";
  echo "Your age is" . $_POST["age"] . "<br>";

?>

會得到:資料有缺,請再次填寫

  • $_GET$_POST 可以混用
    index.php
<form method="POST" action="data.php?gender=female">
  name: <input name="name" />
  age: <input name="age" />
  <input type="submit">
</form>

data.php

<?php
    if (empty($_POST["name"]) || empty($_POST["age"])) {
    echo "資料有缺,請再次填寫<br>";
    exit();
  }

  echo "Hello" . $_POST["name"] . "<br>";
  echo "Your age is" . $_POST["age"] . "<br>";
  echo "Gender:" . $_GET["gender"];

?>

會得到:
HelloYi-De
Your age is26
Gender:female

從 PHP 連線到資料庫

新增使用者

  • 主機名稱:可以從什麼地方連到資料庫

範例

通常會將連線和其他部分分開寫,檔名叫 conn.php,上傳 github 時會拿掉這個檔案,在 .gitignore 裡面放這個檔案(其他檔案要使用此資料庫的話,再用 require_once('conn.php'); 呼叫)

<?php

  $server_name = 'localhost';
  $username = 'yide';
  $password = 'yide';
  $db_name = 'yide';

  $conn = new mysqli($server_name, $username, $password, $db_name);

  if(!empty($conn->connect_error)) {
    die("資料有誤: " . $conn->connect_error);
  }

  $conn->query('SET NAMES UTF8');
  $conn->query('SET time_zone = +"8:00"');

?>

$conn = new mysqli(<server_name>,<username>,<password>,<db_name>)

->

來表示屬性,如果參數有錯,echo $conn->connect_error; 會得到 Unknown database 'yideff',如果有些 PHP 的 server 沒有打開 warning 的設定,這時可以用此語法來 debug

if(!empty($conn->connect_error)) {
    echo "資料有誤: " . $conn->connect_error . "<br>";
  }

die

如果資料有誤,跑完這行就不會繼續執行程式(資料庫有錯,繼續執行下去也沒意義)

if(!empty($conn->connect_error)) {
    die("資料有誤: " . $conn->connect_error);
  }

$conn->query('SET NAMES UTF8');

設定編碼(不設的話,中文會有亂碼)

$conn->query('SET time_zone = +"8:00"');

設定成台灣時區

PHP 與 MySQL 的互動:讀取資料

範例ㄧ:

<?php

  require_once('conn.php');

  $result = $conn->query("select now()"); //"select now()" 可以選到現在的時間

  if(!$result) {
    die($conn->error);
  }
  //print_r($result)

  $row = $result->fetch_assoc();
  //print_r($row);

  echo "now: " . $row['now()'];

print_r($conn->error);

檢視哪邊有錯誤,如果 $result 有錯的話,不會顯示出來,所以可以這樣用:

if(!$result) {
    die($conn->error);
  }
  print_r($result)

$row = $result->fetch_assoc();

print_r($row); 會得到 Array ( [now()] => 2021-06-10 04:23:29 )
echo "now: " . $row['now()']; 可以得到 now: 2021-06-10 04:25:55

範例二:

<?php

  require_once('conn.php');

  $result = $conn->query("select * from users");
  if(!$result) {
    die($conn->error);
  }

  $row = $result->fetch_assoc();
  print_r($row);

?>

$row = $result->fetch_assoc(); print_r($row);

會得到 users 資料表的第一筆資料,要得到兩筆資料需再跑一次 $row = $result->fetch_assoc(); print_r($row);

while ($row = $result->fetch_assoc()) { print_r($row); }

用迴圈拿到所有資料,while 實際上是先跑 $row = $result->fetch_assoc() 再來判斷 $row 是否為空

PHP 與 MySQL 的互動:新增資料

範例一:

<?php
  require_once('conn.php');

  $result = $conn->query("insert into users(username) values('apple')");
  if(!$result) {
    die($conn->error);
  }

  print_r($result)

?>

print_r($result)

為 1,代表 true 的意思,再重新整理,又會再新增一次

values('apple')

需要用單引號,因為外面已經用雙引號了

範例二:

利用 spintf()

<?php
  require_once('conn.php');
  $username = 'Miwa';
  $sql = sprintf(
    "insert into users(id, username) values(%d, '%s')",
    13,
    $username
  );

  $result = $conn->query($sql);
  if(!$result) {
    die($conn->error);
  }

  print_r($result)

?>

範例三:

index.php

<?php
  require_once('conn.php');

  $result = $conn->query("select * from users order by id desc;"); //按照id排序(ASC 由小到大)(DESC 由大到小)
  if(!$result) {
    die($conn->error);
  }

  while ($row = $result->fetch_assoc()) {
    echo "id: " . $row['id'] . "<br>";
    echo "username: " . $row['username'] . "<br>";
  }

?>

<h2>新增 user</h2>
<form method="POST" action="add.php">
  username: <input name="username" />
  <input type="submit">
</form>

add.php

$sql = sprintf("insert into users(username) values('%s')",$username);

<?php
  require_once('conn.php');

  if (empty($_POST['username'])) {
    die('請輸入 username'); //錯誤處理
  }

  $username = $_POST['username'];
  $sql = sprintf(
    "insert into users(username) values('%s')",
    $username
  );

  echo 'SQL:' . $sql . "<br>";

  $result = $conn->query($sql);
  if(!$result) {
    die($conn->error); //錯誤處理
  }

  print_r($result);

  // echo "新增成功"; (因為會直接跳回去 index.php 所以這邊可以省略

  header("Location: index.php"); //跳轉的 header

?>

<!-- <a href="index.php">go back</a> !-->

可以利用 header("Location: index.php");<a href="index.php">go back</a> 跳回到 index.php

PHP 與 MySQL 的互動:刪除資料

index.php

echo " <a href='delete.php?id=". $row['id'] ."'>刪除</a>";

這邊用 GET 來刪除 id 是為了方便示範,但通常可能會用 POST + form 的方式

<?php
  require_once('conn.php');

  $result = $conn->query("select * from users order by id desc;"); //按照id排序(ASC 由小到大)(DESC 由大到小)
  if(!$result) {
    die($conn->error);
  }

  while ($row = $result->fetch_assoc()) {
    echo "id: " . $row['id'] . "<br>";
    echo " <a href='delete.php?id=". $row['id'] ."'>刪除</a>";
    echo "<br>";
    echo "username: " . $row['username'] . "<br>";
  }

?>

<h2>新增 user</h2>
<form method="POST" action="add.php">
  username: <input name="username" />
  <input type="submit">
</form>

delete.php

$sql = sprintf("delete from users where id = %d", $id);

<?php
  require_once('conn.php');

  $id = $_GET['id'];
  $sql = sprintf(
    "delete from users where id = %d",
    $id
  );

  echo 'SQL:' . $sql . "<br>";

  $result = $conn->query($sql);
  if(!$result) {
    die($conn->error);
  }

  if($conn->affected_rows >= 1) { // 代表有幾筆資料受影響,如果為 0,代表沒有有成功但沒有資料受影響,可能是沒有此 id
    echo "刪除成功";
  } else {
    echo "查無資料";
  }

  // header("Location: index.php"); //跳轉的 header

?>

<!-- <a href="index.php">go back</a> !-->

PHP 與 MySQL 的互動:編輯資料

index.php

 <?php
  require_once('conn.php');

  $result = $conn->query("select * from users order by id desc;"); //按照id排序(ASC 由小到大)(DESC 由大到小)
  if(!$result) {
    die($conn->error);
  }

  while ($row = $result->fetch_assoc()) {
    echo "id: " . $row['id'] . "<br>";
    echo " <a href='delete.php?id=". $row['id'] ."'>刪除</a>";
    echo "<br>";
    echo "username: " . $row['username'] . "<br>";
  }

?>

<h2>新增 user</h2>
<form method="POST" action="add.php">
  username: <input name="username" />
  <input type="submit">
</form>

<h2>編輯 user</h2>
<form method="POST" action="update.php">
  id: <input name="id" />
  username: <input name="username" />
  <input type="submit">
</form>

update.php

`$sql = sprintf(

"update users set username='%s' where id =%d",
$username,
$id

);`

 <?php
  require_once('conn.php');

  if (empty($_POST['id']) || empty($_POST['username']) ) {
    die('請輸入 id 與 username');
  }

  $id = $_POST['id'];
  $username = $_POST['username'];
  $sql = sprintf(
    "update users set username='%s' where id =%d",
    $username,
    $id
  );

  echo 'SQL:' . $sql . "<br>";

  $result = $conn->query($sql);
  if(!$result) {
    die($conn->error);
  }


  /* if($conn->affected_rows >= 1) { // 代表有幾筆資料受影響,如果為 0,代表沒有有成功但沒有資料受影響,可能是沒有此 id
    echo "編輯成功";
  } else {
    echo "查無資料";
  }
  */



  header("Location: index.php"); //跳轉的 header

?>

<!-- <a href="index.php">go back</a> !-->









Related Posts

React-[入門篇]-在JSX中加入inline style樣式 | 引入 external css 檔案

React-[入門篇]-在JSX中加入inline style樣式 | 引入 external css 檔案

DAY23:Build a pile of Cubes

DAY23:Build a pile of Cubes

[ 學習筆記系列 ] 網頁本質 (一) - HTML 篇

[ 學習筆記系列 ] 網頁本質 (一) - HTML 篇


Comments